#!/usr/bin/perl
#################################################################
# replacebugsite.pl
#
# Copyright (c) 2019, HighGo Software Inc
#
# src/tools/hgchange/replacebugsite.pl
#
#################################################################

use strict;
use warnings;

use File::Find;
use File::Basename;
use Tie::File;

my $pg_bug_site1      = 'pgsql-bugs@postgresql.org';
my $pg_bug_site2      = 'pgsql-bugs@lists.postgresql.org';
my $hg_bug_site      = 'support@highgo.com';
# Use to calculate the time we exec the script
my $time1;
my $time2;
my $time3;

$time1 = time();
find({ wanted => \&wanted, no_chdir => 1 }, '.');

sub wanted
{

	# prevent corruption of git indexes by ignoring any .git/
	if (basename($_) eq '.git')
	{
		$File::Find::prune = 1;
		return;
	}

	return if !-f $File::Find::name || -l $File::Find::name;

	return if ($_ =~ m/\.(ico|bin)$/);
	return if ($_ =~ m/.*replace_bug_site.pl$/);
	#print "Search file $_\n";

	my @lines;
	tie @lines, "Tie::File", $File::Find::name;

	foreach my $line (@lines)
	{
		my $str1;
		my $str2;
		my $position;
		my $pg_bug_site;
		# We only care about lines with a pg bug site.
		if($line =~ m/.*$pg_bug_site1.*/i)
		{
			$pg_bug_site = $pg_bug_site1;
		}
		elsif($line =~ m/.*$pg_bug_site2.*/i)
		{
			$pg_bug_site = $pg_bug_site2;
		}
		else
		{
			next;
		}
		# calculate the $pg_bug_site location in the line
		$position = index($line,$pg_bug_site);
		$str1 = substr($line, 0, $position);
		$str2 = substr($line, $position + length($pg_bug_site));
		# Do a alternative
		$line =~ s/.*$pg_bug_site.*/$str1$hg_bug_site$str2/i;
	}
	untie @lines;
	return;
}
$time2 = time();
$time3 = $time2 - $time1;
print("Cost time:$time3 seconds\n");
